using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Services;
using Identity.Application.Permissions.Interfaces;
using Identity.Application.Roles.Commands;
using MediatR;

namespace Identity.Application.Roles.CommandHandlers;

public class GetRoleByIdCommandHandler : IRequestHandler<GetRoleByIdCommand, Result>
{

    private readonly IRoleService _roleService;
    private readonly IPermissionsReadService _permissionsReadService;

    public GetRoleByIdCommandHandler(IRoleService roleService, IPermissionsReadService permissionsReadService)
    {
        _roleService = roleService;
        _permissionsReadService = permissionsReadService;
    }
    public async Task<Result> Handle(GetRoleByIdCommand request, CancellationToken cancellationToken)
    {
        var role = await _roleService.GetRoleByIdAsync(request.Id);

        if (role == null) return Result.Failure("获取失败");
        var permissions = (await _permissionsReadService.GetListAsync()).Where(p=>role.PermissionIds.Contains(p.Id)).ToList();

        var result = new RoleDto(role.Id,role.Code,role.Name,permissions,role.Description,role.Status,DateTime.UtcNow);

        return Result.Success(result);

    }
}
